<?php

/**
 * 小程序服务商管理系统 v1.0.1
 *
 * 商业运营到axzz.cn官网进行授权使用。
 *
 * (c) cighsen02 <xiayu@959602.com>
 *
 * Create at：2025.03.07
 * Update at: 2025.05.03
*/

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasApiTokens, HasFactory, HasRoles, Notifiable;

    // Guard 名称
    protected $guard_name = 'user';

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    /**
     * 查找给定用户名或邮箱的用户实例。
     *
     * @param string $identifier 用户名或邮箱
     * @return User|null
     */
    public function findForPassport(string $identifier): ?User
    {
        // 检查是否为邮箱格式
        if (filter_var($identifier, FILTER_VALIDATE_EMAIL)) {

            return $this->where('email', $identifier)->first();
        }

        return $this->where('name', $identifier)->first();
    }
}
